define(['app'], function (app) {
    app.controller('userlimits', function ($rootScope, $scope, $http, $modal, $log) {
        // console.log($rootScope.alllimits);
        function init() {
            $http({
                method: 'GET',
                url: '/OSRS/role/list?pageNow=1&pageSize=5',
            }).then(function (res) {
                $scope.roles = res.data.pageDatas;
                console.log($scope.roles);
                $scope.pageSize = res.data.pageSize;
                $scope.pageNow = res.data.pageNow;
                $scope.totalRecords = res.data.totalRecords;
                layui.use(['laypage'], function () {
                    var laypage = layui.laypage;

                    //执行一个laypage实例
                    laypage.render({
                        elem: 'pagination', //注意，这里的 test1 是 ID，不用加 # 号
                        count: $scope.totalRecords,//页总数，从服务端得到
                        curr: $scope.pageNow,
                        limit: $scope.pageSize,
                        jump: function (obj, first) {
                            //首次不执行
                            if (!first) {
                                //obj包含了当前分页的所有参数，比如：
                                $http({
                                    method: 'GET',
                                    url: '/OSRS/role/list?pageNow=' + obj.curr + '&pageSize=' + obj.limit + "&" + $scope.search,
                                }).then(function (res) {
                                    $scope.roles = res.data.pageDatas;
                                    $scope.totalRecords = res.data.totalRecords;
                                    $scope.pageNow = res.data.pageNow;
                                    $scope.pageSize = res.data.pageSize;
                                });

                            }
                        }
                    });


                })


            });


        }

        $http({
            method: 'GET',
            url: '/OSRS/role/list?pageNow=1&pageSize=5',
        }).then(function (res) {
            $scope.roles = res.data.pageDatas;
            console.log($scope.roles);
            $scope.pageSize = res.data.pageSize;
            $scope.pageNow = res.data.pageNow;
            $scope.totalRecords = res.data.totalRecords;


            layui.use(['element', 'form', 'laypage'], function () {
                window.form = layui.form;
                var laypage = layui.laypage,
                    element = layui.element;

                form.render();
                //监听提交
                form.on('submit(addrole)', function (data) {

                    $http({
                        method: 'POST',
                        url: '/OSRS/role/add',
                        data: JSON.stringify(data.field)
                    }).then(function (res) {

                        if (res.data == 'ok') {
                            layer.msg("添加成功");
                            layer.close(addlayer);
                            init();
                        } else if (res.data == '1') {
                            layer.msg("用户名重复");
                        }
                    }, function (err) {
                        layer.msg("服务器未响应");
                    });

                    return false;
                });


                form.on('submit(mod)', function (data) {

                    var r = document.getElementsByName("rightids");
                    var ids = "";
                    for (var i = 0; i < r.length; i++) {
                        if (r[i].checked) {
                            ids += r[i].value;
                            ids += ",";

                        }
                    }


                    ids = ids.substring(0, ids.length - 1);

                    ids = changeroleid + ":" + ids;
                    $http({
                        method: "post",
                        url: "/OSRS/role/addrights",
                        data: ids
                    }).then(function (res) {
                        if (res.data == "ok") {
                            layer.msg("修改成功");
                        } else {
                            alert("修改失败");
                        }
                    }, function (err) {

                        alert("服务器未响应");

                    });


                    $rootScope.cancel();

                    return false;
                });
                //执行一个laypage实例
                laypage.render({
                    elem: 'pagination', //注意，这里的 test1 是 ID，不用加 # 号
                    count: $scope.totalRecords,//页总数，从服务端得到
                    curr: $scope.pageNow,
                    limit: $scope.pageSize,
                    jump: function (obj, first) {
                        //首次不执行
                        if (!first) {
                            //obj包含了当前分页的所有参数，比如：
                            $http({
                                method: 'GET',
                                url: '/OSRS/role/list?pageNow=' + obj.curr + '&pageSize=' + obj.limit + "&" + $scope.search,
                            }).then(function (res) {
                                $scope.roles = res.data.pageDatas;
                                $scope.totalRecords = res.data.totalRecords;
                                $scope.pageNow = res.data.pageNow;
                                $scope.pageSize = res.data.pageSize;
                            });

                        }
                    }
                });

            });


        }, function (err) {

        });

        $scope.all = false;
        $scope.allChk = function () {
            $scope.roles.map(function (value) {
                value.chk = $scope.all;
                return value;
            })
        };

        $scope.layer_delete = function () {
            var r = document.getElementsByName("roleids");
            var ids = "";
            var names = "";
            for (var i = 0; i < r.length; i++) {
                if (r[i].checked) {
                    ids += r[i].value;
                    ids += ",";
                    names += $scope.roles[i].rolename;
                    names += "  ";

                }
            }

            if (ids != "") {
                ids = ids.substring(0, ids.length - 1);
                layer.open({
                    content: '确认要删除 :' + names + '?'
                    , btn: ['确定', '取消']
                    , btn1: function (index, layero) {
                        $http({
                            method: 'post',
                            url: '/OSRS/role/delete',
                            data: ids
                        }).then(function (res) {
                            if (res.data == "ok") {
                                layer.msg("删除成功");
                                init();
                            }
                        });
                    }
                    , btn2: function (index, layero) {

                    }
                    , cancel: function () {
                        //右上角关闭回调

                        //return false 开启该代码可禁止点击该按钮关闭
                    }
                });


            }

        };

        $scope.layer_roleadd = function () {
            addlayer = layer.open({
                type: 1,
                title: "新增用户",
                area: ['640px', '300px'],
                content: `
				<form class="layui-form" id="layerform" > 
				  <div class="layui-form-item">
				    <label class="layui-form-label">角色名</label>
				    <div class="layui-input-block">
				      <input type="text" name="rolename" required  lay-verify="required" placeholder="请输入角色名" autocomplete="off" class="layui-input">
				    </div>
				  </div>
				   
				  <div class="layui-form-item layui-form-text">
				    <label class="layui-form-label">备注</label>
				    <div class="layui-input-block">
				      <textarea name="remark" placeholder="请输入备注" class="layui-textarea"></textarea>
				    </div>
				  </div>
				  <div class="layui-form-item">
				    <div class="layui-input-block">
				      <button class="layui-btn" lay-submit lay-filter="addrole">确认新增</button>
				      <button type="reset" class="layui-btn layui-btn-primary">重置</button>
				    </div>
				  </div>
				</form>
				`
            })
            form.render();

        };

        $scope.layer_limitsmod = function (x) {
            changeroleid = x;

            $http({
                method: 'GET',
                url: '/OSRS/role/allrights?roleid=' + x,
            }).then(function (res) {
                $rootScope.alllimits = res.data;

                modalInstance = $modal.open({
                    title: "权限设置",
                    keyboard: true,
                    controller: ModalInstanceCtrl,
                    resolve: {
                        items: function () {

                            return $rootScope.alllimits;
                        }
                    },
                    windowClass: 'limitsele-Modal',
                    template: `
				<p class="layui-layer-title">权限设置</p>
				<form class="layui-form" id="limitssele">
		  			<div class="limitssele">
						<ul class="layui-text" ng-repeat="x in alllimits track by $index" ng-init="index=$index">
							<h3><input  type="checkbox" class="limitsele" ng-model="x.state" ng-change="sele(x)" /> {{x.title}}</h3>
							<li class="" ng-repeat="y in x.rights track by $index">
								<input name="rightids" value="{{y.rightid}}" type="checkbox" class="limitsele" ng-model="y.state" ng-change="itemsele(y,index,$index,y.state)" /> {{y.ctrname}}
							</li>
						</ul>
					</div>
				  <div class="layui-form-item">
				    <div class="layui-input-block">
				      <button class="layui-btn" lay-submit lay-filter="mod">确认修改</button>
				    	  <button class="layui-btn layui-btn-primary" ng-click="cancel()">取消</button>
				    </div>
				  </div>
				</form>
				`

                });
                form.render();


            }, function (err) {

            });

        };


        var ModalInstanceCtrl = function ($scope, $modalInstance, items) {
//			$scope.items = items;
//			$scope.selected = {
//				item: $scope.items = []
//			};
//			$rootScope.ok = function() {
//				$modalInstance.close($scope.selected);
//			};
            $rootScope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };
        };

        $rootScope.sele = function (x) {

            for (var i = 0; i < x.rights.length; i++) {
                x.rights[i].state = x.state;
            }
        };

        $rootScope.itemsele = function (y, parentindex, index, state) {

            console.log(y, parentindex, index, state);

            if (!state) {
                $rootScope.alllimits[parentindex].state = false;
            } else {
                for (var i = 0; i < $rootScope.alllimits[parentindex].length; i++) {
                    if (!$rootScope.alllimits[parentindex].rights[i]) {
                        return 0;
                    }
                }

                $rootScope.alllimits[parentindex].state = true;
            }
        };


    })
});
